package com.inray.nbs.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.inray.nbs.bean.Userinfo;
import com.inray.nbs.bean.Userlog;
import com.inray.nbs.service.UserSetService;
import com.inray.nbs.utils.MD5;
import com.inray.nbs.vo.Menu;
import com.inray.nbs.vo.MiniTree;
import com.inray.nbs.vo.VehicleNum;

/**
 * 用户控制类
 * UserSetController
 * @author Ming Yang
 *
 */
@Controller
@RequestMapping(value = "/userset")
public class UserSetController {
	
	@Resource
	private UserSetService setService;
	
	/**
	 * 加载人员列表
	 * @throws IOException 
	 */
	@RequestMapping(value = "/selectUserData.do", method=RequestMethod.POST  )
	@ResponseBody
	public void selectWmsUserData(HttpServletRequest request, HttpServletResponse response) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		Userinfo user = (Userinfo) request.getSession().getAttribute("user");
		if(user!=null){
			if(user.getUserid()!=1){
				map.put("userid", user.getUserid());
			}
		}
		int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
	    int pageSize = Integer.parseInt(request.getParameter("pageSize")); 
		String username = request.getParameter("username");
		if(username!=null&&!"".equals(username.trim())){
			map.put("username","%"+username+"%");
		}
		List<Userinfo> list =setService.selectUserData(map);
		int total = list.size();
		String sortField=request.getParameter("sortField");
	    String sortOrder=request.getParameter("sortOrder");
		if(sortField!=null&&sortOrder!=null){
			if(!"".equals(sortField)&&!"".equals(sortOrder)){
				map.put("sortField","a."+sortField+" "+sortOrder);
			}else{
				map.put("sortField","a.userid asc");
			}
		}else{
			map.put("sortField","a.userid asc");
		}
		map.put("rows",  (pageIndex+1)*pageSize);
		map.put("offset",((pageIndex+1)-1)* pageSize);
		JSONObject result = new JSONObject();
		result.clear();
		result.put("total",total);
		
		List<Userinfo> rslst = new ArrayList<Userinfo>();
		int index=0;
		for(Userinfo u:list){
			int num=0;
			if((u.getUserid()).equals(user.getUserid())||(u.getUserid()).equals(1)){
				
			}else {
				if(u.getVehicleids()!=null&&!"".equals(u.getVehicleids())){
					String[] arr = u.getVehicleids().split(",");
					num=arr.length;
				}
				if(num>0){
					u.setVehiclenum(num+" 辆");
				}else{
					u.setVehiclenum("全部");
				}
				rslst.add(u);
			}
		}
		result.put("data", rslst);
		String json = JSON.toJSONStringWithDateFormat(result, "yyyy-MM-dd HH:mm:ss");
		response.getWriter().write(json);
	}
	
//	/**
//	 * 加载用户所有菜单
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value = "/selectMenuAll.do", method=RequestMethod.POST  )
//	@ResponseBody
//	public String selectMenuAll(HttpServletRequest request){
//		Userinfo user = (Userinfo)request.getSession().getAttribute("user");
//		Map<String,Object> map = new HashMap<String,Object>();
//		if(user.getRoleid()!=0){
//			if(!"".equals(user.getRoleids())&&!"0".equals(user.getRoleids())){
//				String[] arr  = user.getRoleids().split(",");
//				map.put("rolemenus", arr);
//			}
//		}
//		List<Rolemenu> list = setService.selectMenuAll(map);
//		List<Rolemenu> rslst = new ArrayList<Rolemenu>();
//		List<Rolemenu> onelst = new ArrayList<Rolemenu>();
//		for(Rolemenu r:list){
//			if(r.getParnid()==0){
//				onelst.add(r);
//			}
//		}
//		for(Rolemenu r:onelst){
//			List<Rolemenu> twolst = new ArrayList<Rolemenu>();
//			for(Rolemenu r1:list){
//				if(r.getRolemenu()==r1.getParnid()){
//					twolst.add(r1);
//				}
//			}
//			r.setLst(twolst);
//			rslst.add(r);
//		}
//		JSONArray json=new JSONArray();
//		return json.fromObject(rslst).toString();
//	}
	/**
	 * 添加人员
	 */
	@RequestMapping(value = "/AddUserData.do", method=RequestMethod.POST  )
	@ResponseBody
	public String AddUserData(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String result="1";
	    try {
			String json = request.getParameter("data");
			List<String> list = JSON.parseObject(json, new TypeReference<List<String>>() {});
			int size =list.size()-1;
			for(int i=size;i>=0; i--){
				Userinfo row=JSON.parseObject(list.get(i), Userinfo.class);
				row.setLoginpassword(MD5.getPsw(row.getLoginpassword()));
				result=String.valueOf(setService.addUser(row));
			}
		} catch (Exception e) {
			result=e.getMessage();
			e.printStackTrace();
		}
	    return result;
	}
	/**
	 * 强行修改用户信息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ForcedUser.do", method=RequestMethod.POST  )
	@ResponseBody
	public String ForcedUser(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String result="1";
	    try {
			String json = request.getParameter("data");
			List<String> list = JSON.parseObject(json, new TypeReference<List<String>>() {});
			int size =list.size()-1;
			for(int i=size;i>=0; i--){
				Userinfo row=JSON.parseObject(list.get(i), Userinfo.class);
				if(row.getLoginpassword()!=null&&!"".equals(row.getLoginpassword())){
					row.setLoginpassword(MD5.getPsw(row.getLoginpassword()));
				}else{
					row.setLoginpassword(null);
				}
				if(row.getUserid()==1&&row.getRoleid()!=0){
					row.setRoleid(0);
				}
				if(row.getUserid()==1&&row.getState()!=1){
					row.setState(1);
				}
				result=String.valueOf(setService.ForcedUser(row));
			}
		} catch (Exception e) {
			result=e.getMessage();
			e.printStackTrace();
		}
	    return result;
	}
	/**
	 * 分配管控车辆
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/SaveCtrlVehicle.do", method=RequestMethod.POST  )
	@ResponseBody
	public String SaveCtrlVehicle(HttpServletRequest request, HttpServletResponse response,Userinfo user) throws Exception
	{
		String result="1";
	    try {
	    	if(user.getVehicleids()==null||"".equals(user.getVehicleids())){
	    		user.setVehicleids(null);
	    	}
	    	result=String.valueOf(setService.SaveCtrlVehicle(user));
		} catch (Exception e) {
			result=e.getMessage();
			e.printStackTrace();
		}
	    return result;
	}
	/**
	 * 更新管控车辆数
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/GetPositionsByVehicle.do", method=RequestMethod.POST  )
	@ResponseBody
	public void GetPositionsByVehicle(HttpServletRequest request, HttpServletResponse response,Integer num) throws Exception
	{
	    List<VehicleNum> data = new ArrayList<VehicleNum>();
	    VehicleNum v = new VehicleNum();
	    v.setId(num);
	    v.setName(String.valueOf(num));
	    data.add(v);
	    String json = com.inray.nbs.utils.JSON.Encode(data);
	    response.getWriter().write(json);
	}
	/**
	 * 人员编辑保存
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/SaveUserData.do", method=RequestMethod.POST  )
	@ResponseBody
	public String SaveUserData(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String result="1";
	    try {
			String json = request.getParameter("data");
			List<String> list = JSON.parseObject(json, new TypeReference<List<String>>() {});
			int size =list.size()-1;
			for(int i=size;i>=0; i--){
				Map<String, String> ssMap = JSON.parseObject(list.get(i), new TypeReference<Map<String, String>>() {});
			    String state = ssMap.get("_state");
			    if (state.equals("removed") || state.equals("deleted"))
			    {
			    	Userinfo row=JSON.parseObject(list.get(i), Userinfo.class);
			    	if(row.getUserid()!=1){
			    		result=String.valueOf(setService.delUser(row));
			    	}
			    }
			    else if (state.equals("modified") || state.equals(""))	
			    {
			    	Userinfo row=JSON.parseObject(list.get(i), Userinfo.class);
			    	if(row.getUserid()==1&&row.getState()==0){
			    		row.setState(1);
			    	}
			    	result=String.valueOf(setService.editUser(row));     
			    }
			}
		} catch (Exception e) {
			result=e.getMessage();
			e.printStackTrace();
		}
	    return result;
	}
	/**
	 * 验证用户名是否存在
	 * @param request
	 * @param info
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/CheackLoginname.do", method=RequestMethod.POST  )
	@ResponseBody
	public String CheackLoginname(HttpServletRequest request,String loginname) throws Exception
	{
		String result="1";
	    try {
	    	Map<String,Object> map  = new HashMap<String,Object>();
	    	if(loginname!=null&&!"".equals(loginname)){
	    		map.put("loginname", loginname);
	    	}
			List<Userinfo> lst = setService.CheackLoginname(map);
			if(lst.size()>0){
				result="2";
			}
		} catch (Exception e) {
			result=e.getMessage();
			e.printStackTrace();
		}
	    return result;
	}
	
	/**
	 * 密码邮箱修改
	 * @param request
	 * @param tray
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/EditPassword.do",method=RequestMethod.POST)
	@ResponseBody
	public String EditPassword(HttpServletRequest request,Userinfo newuser) throws UnsupportedEncodingException{
		JSONObject json=new JSONObject();
		try{
			Userinfo user = (Userinfo) request.getSession().getAttribute("user");
			String oldpaw = MD5.getPsw(newuser.getOldpaw());
			if(oldpaw.equals(user.getLoginpassword())){
				if(newuser.getEditmode()==1){
					user.setLoginpassword(MD5.getPsw(newuser.getNewpaw()));
					user.setEmail(null);
				}else{
					user.setLoginpassword(null);
					user.setEmail(newuser.getEmail());
				}
				int i=setService.EditPaswEmail(user);
				if(i>0){
					json.put("success", "success");
				}else{
					json.put("success", "no");
				}
			}else{
				json.put("success", "pawerror");
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			json.put("success", "no");
		}
		return json.toString();
	}
	/**
	 * 加载用户登录记录
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/selectLoginLogData.do", method=RequestMethod.POST  )
	@ResponseBody
	public void selectLoginLogData(HttpServletRequest request, HttpServletResponse response) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
	    int pageSize = Integer.parseInt(request.getParameter("pageSize")); 
		String userid = request.getParameter("userid");
		if(userid!=null&&!"".equals(userid.trim())){
			map.put("userid",Integer.parseInt(userid));
		}
		int total = setService.selectLoginLogData(map).size();
		String sortField=request.getParameter("sortField");
	    String sortOrder=request.getParameter("sortOrder");
		if(sortField!=null&&sortOrder!=null){
			if(!"".equals(sortField)&&!"".equals(sortOrder)){
				map.put("sortField","a."+sortField+" "+sortOrder);
			}else{
				map.put("sortField","a.logid desc");
			}
		}else{
			map.put("sortField","a.logid desc");
		}
		map.put("rows",  (pageIndex+1)*pageSize);
		map.put("offset",((pageIndex+1)-1)* pageSize);
		JSONObject result = new JSONObject();
		result.clear();
		result.put("total",total);
		List<Userlog> list =setService.selectLoginLogData(map);
		result.put("data", list);
		String json = JSON.toJSONStringWithDateFormat(result, "yyyy-MM-dd HH:mm:ss");
		response.getWriter().write(json);
	}
}
